/*
 * Sapphire
 *
 * Copyright (C) 2018 Alyssa Rosenzweig
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 *
 */

/* Utility for transforming plain text into emojified version */

window.emojify = function(text) {
    return emoticonToEmojify(colonEmojify(text));
};

/* Transform :emoji: to its Unicode equivalent */

const colonEmojify = function(text) {
    return text.replace(/:[^ :]*:/g, (pattern) => {
        const raw = pattern.slice(1, -1).toLowerCase();

        /* Put it into the two normal forms, underscores or hyphen, and try
         * each */

        const underscore = raw.replace(/-/g, '_');

        if (window.EMOJIS[underscore])
            return window.EMOJIS[underscore];

        const hyphen = raw.replace(/_/g, '-');

        if (window.EMOJIS[hyphen])
            return window.EMOJIS[hyphen];

        /* Try it as a country name */

        const spaced = raw.replace(/[-_]/g, ' ');
        const country = window.COUNTRY_NAME_TO_ID[spaced];

        if (country) {
            const flagName = 'flag-' + country;

            if (window.EMOJIS[flagName])
                return window.EMOJIS[flagName];
        }

        /* Otherwise, give up and return as-is */

        return pattern;
    });
};

/* Transform :p to Unicode */
const emoticonToEmojify = function(s) {
    return s.split(' ').map(w => window.EMOTICON_TO_UNICODE[w] || w).join(' ');
};
